<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
<!--        <el-button type="danger"-->
<!--                   size="small"-->
<!--                   icon="el-icon-delete"-->
<!--                   plain-->
<!--                   v-if="permission.purchase_delete"-->
<!--                   @click="handleDelete">删 除-->
<!--        </el-button>-->
      </template>
      <template slot="menu" slot-scope="scope">
        <el-button v-if="scope.row.platform === '拼多多'" type="text" style="font-size: 12px;" @click="handleOpenDetail(scope.row)">
          订单详情页
        </el-button>
      </template>
      <template slot="status"  slot-scope="scope">
        <el-tag> {{ scope.row.statusName }} </el-tag>
      </template>
      <template slot="search" slot-scope="{row,size}">
        <div class="el-form-item el-form-item--small avue-form__item--">
          <label class="el-form-item__label" >下单时间：</label>
          <el-date-picker
            style="margin-right: 10px; width: 300px !important; height: 32px; line-height: 32px;"
            v-model="dateRange"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd 00:00:00"
            :picker-options="pickerOptions">
          </el-date-picker>
        </div>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/purchase/purchase";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          refreshBtn: false,
          column: [
            {
              label: "店铺名称",
              prop: "userName",
              rules: [{
                required: true,
                trigger: "blur"
              }],
              search: true,
              type: 'select',
              dicUrl: "/api/celery-shop/shop/shop_select",
              props: {
                label: "label",
                value: "label"
              },
            },
            {
              label: "关联订单",
              prop: "ticketId",
              rules: [{
                required: true,
                message: "请输入关联的订单号",
                trigger: "blur"
              }],
              // type: 'select',
              // dicUrl: "/api/celery-ticket/ticket/purchase-ticket-list",
              // props: {
              //   label: "id",
              //   value: "id"
              // },
            },
            // {
            //   label: "采购号",
            //   prop: "purchaseNum",
            //   rules: [{
            //     required: true,
            //     message: "请输入采购号",
            //     trigger: "blur"
            //   }]
            // },
            {
              label: "采购平台",
              prop: "platform",
              rules: [{
                required: true,
                message: "请输入采购平台",
                trigger: "blur"
              }],
              type: 'select',
              dicData: [
                {
                  value: '供应商'
                },
                {
                  value: '拍单插件'
                }
              ],
              props: {
                label: "value",
                value: "value"
              },
            },
            {
              label: "采购单",
              prop: "purchaseCode",
              rules: [{
                required: true,
                message: "请输入采购单",
                trigger: "blur"
              }]
            },
            {
              label: "状态",
              prop: "status",
              slot: true,
              type: 'select',
              dicData: [
                {
                  value: 1,
                  label: '未付款'
                },
                {
                  value: 2,
                  label: '拼单进行中'
                },
                {
                  value: 3,
                  label: '拼单成功，待发货'
                },
                {
                  value: 4,
                  label: '交易取消'
                },
                {
                  value: 5,
                  label: '已发货'
                },
                {
                  value: 6,
                  label: '已收货'
                }
              ],
              props: {
                label: "label",
                value: "value"
              },
            },
            {
              label: "下单时间",
              prop: "createTime",
              type: "datetime",
              format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "yyyy-MM-dd hh:mm:ss"
            },
            {
              label: "价格",
              prop: "amount",
              rules: [{
                required: true,
                message: "请输入价格",
                trigger: "blur"
              }]
            },
            // {
            //   label: "数量",
            //   prop: "count",
            //   rules: [{
            //     required: true,
            //     message: "请输入数量",
            //     trigger: "blur"
            //   }]
            // },
            // {
            //   label: "商家id",
            //   prop: "mailId",
            //   rules: [{
            //     required: true,
            //     message: "请输入商家id",
            //     trigger: "blur"
            //   }]
            // },
            {
              label: "商家名称",
              prop: "mailName",
              rules: [{
                required: true,
                message: "请输入商家名称",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "remark",
              span: 24,
              type: 'textarea'
            },
          ]
        },
        data: [],
        dateRange: '',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
              picker.$emit('pick', [start, end]);
            }
          }]
        }
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: true,
          viewBtn: false,
          delBtn: true,
          editBtn: true
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleOpenDetail(row) {
        if (!row.purchaseCode || row.purchaseCode === '') {
          this.$message.warning("未获取到拼多多订单号！")
          return
        }
        window.open(`https://mobile.yangkeduo.com/order.html?order_sn=${row.purchaseCode}`)
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.dateRange = ''
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        if (this.dateRange && this.dateRange !== '') {
          params.createTimeStart = this.dateRange[0]
          params.createTimeEnd = this.dateRange[1]
        }
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
.el-input__icon {
  height: auto;
}
</style>
